package team.seekers.skill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;
import team.seekers.skill.entity.dao.Section;
import team.seekers.skill.entity.dao.SectionBlog;
import team.seekers.skill.entity.dao.SectionVideo;
import team.seekers.skill.entity.query.SectionQuery;
import team.seekers.skill.entity.vo.admin.add.AdminBlogAddVO;
import team.seekers.skill.entity.vo.admin.add.AdminSectionAddVO;
import team.seekers.skill.entity.vo.admin.add.AdminVideoAddVO;
import team.seekers.skill.entity.vo.admin.list.AdminSectionListVO;
import team.seekers.skill.entity.vo.admin.update.AdminSectionUpdateVO;
import team.seekers.skill.entity.vo.fore.list.SectionListVO;
import team.seekers.skill.entity.vo.fore.detail.SectionDetailVO;
import team.seekers.skill.result.Result;
import team.seekers.skill.result.ResultCode;
import team.seekers.skill.service.SectionBlogService;
import team.seekers.skill.service.SectionService;
import team.seekers.skill.service.SectionVideoService;
import team.seekers.skill.common.utils.ParamCheckUtils;
import team.seekers.skill.common.utils.SkillUtils;

import java.util.ArrayList;
import java.util.List;

import static team.seekers.skill.result.ResultCode.GET_FAIL;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hbc
 * @since 2021-01-18
 */
@RestController
@RequestMapping("/api/skill/section")
@Validated
public class SectionController {

    @Autowired
    private SectionService sectionService;
    @Autowired
    private SectionBlogService sectionBlogService;
    @Autowired
    private SectionVideoService sectionVideoService;

    //获取某章下所有的节
    @GetMapping("/listSectionVOByChapterId/{chapterId}")
    @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
    public Result listSectionVOByChapterId(@PathVariable("chapterId")String chapterId){
        if(ParamCheckUtils.isNotRightId(chapterId)){
            return Result.fail(ResultCode.MAIN_GET_FAIL);
        }
        List<SectionListVO> sectionListVOList =  sectionService.listSectionVOByChapterId(chapterId,SkillUtils.getUserId());
        if (sectionListVOList == null){
            return Result.fail(ResultCode.GET_FAIL);
        }
        return Result.success().data("rows", sectionListVOList);
    }

    //开始学习某一节（标记学习状态为已学习，生成对应笔记区）
    @GetMapping("/startLearn/{sectionId}")
    @PreAuthorize("hasRole('ROLE_USER')")
    public Result startLearn(@PathVariable("sectionId")String sectionId){
        if(ParamCheckUtils.isNotRightId(sectionId)){
            return Result.fail(ResultCode.PARAM_NOT_VALID);
        }
        boolean learn = sectionService.startLearn(sectionId,SkillUtils.getUserId());
        if (!learn){
            return Result.fail(ResultCode.ACTION_FAIL);
        }
        return Result.success();
    }

    //结束学习某一节（标记学习状态为已学习，生成对应笔记区）
    @GetMapping("/endLearn/{sectionId}")
    @PreAuthorize("hasRole('ROLE_USER')")
    public Result endLearn(@PathVariable("sectionId")String sectionId){
        if(ParamCheckUtils.isNotRightId(sectionId)){
            return Result.fail(ResultCode.PARAM_NOT_VALID);
        }
        boolean learn = sectionService.endLearn(sectionId,SkillUtils.getUserId());
        if (!learn){
            return Result.fail(ResultCode.ACTION_FAIL);
        }
        return Result.success();
    }

    @GetMapping("/get/{sectionId}")
    @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
    public Result get(@PathVariable("sectionId")String sectionId){
        if(ParamCheckUtils.isNotRightId(sectionId)){
            return Result.fail(ResultCode.PARAM_NOT_VALID);
        }
        SectionDetailVO sectionDetailVO = sectionService.getSectionDetailVO(sectionId);
        if(sectionDetailVO == null){
            return Result.fail(ResultCode.GET_FAIL);
        }
        return Result.success("VO",sectionDetailVO);

    }


    //增加
    @PostMapping("/add")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result add(@RequestBody AdminSectionAddVO adminSectionAddVO){
        Section section = new Section();
        BeanUtils.copyProperties(adminSectionAddVO,section);
        boolean save = sectionService.save(section);
        if (!save) {
            return Result.fail(ResultCode.ACTION_FAIL);
        }
        List<AdminBlogAddVO> adminBlogAddVOS = adminSectionAddVO.getBlogAddVOList();
        for (AdminBlogAddVO adminBAddVO : adminBlogAddVOS) {
            SectionBlog sectionBlog = new SectionBlog();
            BeanUtils.copyProperties(adminBAddVO,section);
            sectionBlog.setSectionId(section.getId());
            save = sectionBlogService.save(sectionBlog);
            if (!save) {
                return Result.fail(ResultCode.ACTION_FAIL);
            }
        }

        List<AdminVideoAddVO> adminVideoAddVOS = adminSectionAddVO.getVideoAddVOList();
        for (AdminVideoAddVO adminVideoAddVO : adminVideoAddVOS) {
            SectionVideo sectionVideo = new SectionVideo();
            BeanUtils.copyProperties(adminVideoAddVO,sectionVideo);
            sectionVideo.setSectionId(section.getId());
            save = sectionVideoService.save(sectionVideo);
            if (!save) {
                return Result.fail(ResultCode.ACTION_FAIL);
            }
        }
        return Result.success();
    }

    //删除
    @DeleteMapping("/delete/{sectionId}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result delete(@PathVariable("sectionId") String sectionId){
        if (ParamCheckUtils.isNotRightId(sectionId)){
            return Result.fail(ResultCode.PARAM_NOT_VALID);
        }
        boolean delete = sectionService.delete(sectionId);
        if(!delete){
            return Result.fail(ResultCode.ACTION_FAIL);
        }
        return Result.success();
    }


    //修改
    @PutMapping("/update")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result update(@RequestBody AdminSectionUpdateVO adminSectionUpdateVO){
        if(ParamCheckUtils.isNotRightId(adminSectionUpdateVO.getId())){
            return Result.fail(ResultCode.PARAM_NOT_VALID);
        }
        Section section = sectionService.getById(adminSectionUpdateVO.getId());
        BeanUtils.copyProperties(adminSectionUpdateVO,section);
        boolean b = sectionService.updateById(section);
        if(!b){
            return Result.fail(ResultCode.ACTION_FAIL);
        }
        return Result.success();
    }


    //分页查询（标题模糊查询）
    @PostMapping("/pageNewsCondition/{current}/{limit}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result pageNewsCondition(@PathVariable("current") long current,
                                    @PathVariable("limit") long limit,
                                    @RequestBody SectionQuery sectionQuery) {
        //创建page对象
        Page<Section> pageNews = new Page<>(current, limit);
        QueryWrapper<Section> wrapper = new QueryWrapper<>();
        String title = sectionQuery.getTitle();
        if (!StringUtils.isEmpty(title)) {
            wrapper.like("title", title);
        }
        String skillId = sectionQuery.getSkillId();
        if (!StringUtils.isEmpty(skillId)) {
            if(ParamCheckUtils.isNotRightId(skillId)){
                return Result.fail(ResultCode.PARAM_NOT_VALID);
            }
            wrapper.eq("skill_id", skillId);
        }
        String chapterId = sectionQuery.getSkillId();
        if (!StringUtils.isEmpty(chapterId)) {
            if(ParamCheckUtils.isNotRightId(chapterId)){
                return Result.fail(ResultCode.PARAM_NOT_VALID);
            }
            wrapper.eq("chapter_id", chapterId);
            wrapper.orderByDesc("sequence");
        }
        String begin = sectionQuery.getBegin();
        if(!org.springframework.util.StringUtils.isEmpty(begin)){
            wrapper.ge("update_date",begin);
        }
        String end = sectionQuery.getEnd();
        if (!org.springframework.util.StringUtils.isEmpty(end)){
            wrapper.le("update_date",end);
        }
        //调用方法实现条件分页查询(按照章节排序的先后顺序)
        sectionService.page(pageNews, wrapper);
        long total = pageNews.getTotal();
        List<Section> records = pageNews.getRecords();
        if(records == null){
            return Result.fail(GET_FAIL);
        }
        List<AdminSectionListVO> voList = new ArrayList<>();
        for (Section record : records) {
            AdminSectionListVO adminSectionListVO = new AdminSectionListVO();
            BeanUtils.copyProperties(record,adminSectionListVO);
            voList.add(adminSectionListVO);
        }
        return Result.success().data("total", total).data("rows", voList);
    }

}

